<?php
declare(strict_types=1);

namespace app\model;


use think\Model;
use app\exceptions\SystemException;
use think\facade\Db;

class Message extends Model
{
    protected $table = 'test_user_chat_service';

    //is_deleted 0-未删除，1-已删除
    const IS_DELETED = 1;
    const NO_DELETED = 0;

    //status 0-未读，1-已读
    const READ = 1;
    const UN_READ = 0;

    //用户标记删除状态，1：删除，0：未删除
    const U_IS_DELETED = 1;
    const U_NO_DELETED = 0;

    //客服专员标记删除状态，1：删除，0：未删除
    const S_IS_DELETED = 1;
    const S_NO_DELETED = 0;


    /**
     * 用户发消息给客服
     * @param array $data
     * @return bool
     * @throws SystemException
     * @throws \think\exception\PDOException
     */
    public function insertMessageByUser(array $data)
    {
        #todo  message使用jwt加密。
        Db::startTrans();
        try {
            $this->insert([
                'uid' => $data['uid'],
                'from_client_id' => $data['uid'],
                'server_uid' => serviceUid(),
                'to_client_id' => serviceUid(),
                'message' => $data['message'],
                'create_time' => time(),
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new SystemException($e->getMessage());
        }
        return true;
    }

    /**
     * 客服发消息给用户
     * @param array $data
     * @return bool
     * @throws SystemException
     * @throws \think\exception\PDOException
     */
    public function insertMessageByCustomerService(array $data)
    {
        Db::startTrans();
        try {
            $this->insert([
                'uid' => $data['to_uid'],
                'from_client_id' => serviceUid(),
                'server_uid' => serviceUid(),
                'to_client_id' => $data['to_uid'],
                'message' => $data['message'],
                'create_time' => time(),
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new SystemException($e->getMessage());
        }
        return true;
    }

    /**
     * 查询指定uid聊天记录
     * @param string $uid
     * @param int $page
     * @param string $delete_type
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getMessageListByUid(string $uid, int $page, string $delete_type = 's')
    {
        //u_deleted
        //s_deleted
        if ($delete_type == 'u') {
            $where = [
                'uid' => $uid,
                'u_deleted' => self::U_NO_DELETED,
            ];
        } else {
            $where = [
                'uid' => $uid,
                's_deleted' => self::S_NO_DELETED,
            ];
        }

        $field = [
            'id',
            'uid',
            'server_uid',
            'from_client_id',
            'to_client_id',
            'message',
            'type',
            'status',
            'create_time',
        ];
        return $this->where($where)->field($field)
            ->where(['is_deleted' => self::NO_DELETED])
            ->paginate([
                'page' => $page,
                'list_rows' => 1200
            ])
            ->toArray();
    }

    /**
     * 查询最新一条记录
     * @param int $start
     * @param int $limit
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     */
    public function getLastMessage(int $start, int $limit)
    {
        #sql 语句参考： https://blog.csdn.net/fmyzc/article/details/81507989
        $sql = "SELECT * FROM (
SELECT id,uid,server_uid,from_client_id,to_client_id,message,create_time,update_time,is_deleted,`type`,`status` FROM
 test_user_chat_service ORDER BY id DESC LIMIT 100000
)t WHERE t.is_deleted =" . self::NO_DELETED . " GROUP BY t.uid";
        $sql .= " LIMIT " . $start . "," . $limit;
        $query = $query = Db::query($sql);

        return $query;
    }

    /**
     * 查询消息记录总数（最新一条）
     * @return int
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     */
    public function getMessageListTotal()
    {
        $sql = "SELECT count(*) as id FROM (
SELECT id,uid,server_uid,from_client_id,to_client_id,message,create_time,update_time,is_deleted,`type`,`status` FROM
 test_user_chat_service ORDER BY id DESC LIMIT 100000
)t WHERE t.is_deleted =" . self::NO_DELETED . " GROUP BY t.uid  ";
        $query = $query = Db::query($sql);
        return count($query);
    }

    /**
     * 删除全部消息记录
     * @param string $uid
     * @return bool
     */
    public function deletedMessageByUid(string $uid)
    {
        $this->where(['uid' => $uid])
            ->update([
                'is_deleted' => self::IS_DELETED,
                'update_time' => time(),
            ]);

        return true;
    }
}
